package com.partition.mysql.init;


import com.partition.mysql.bean.PartitionItem;
import com.partition.mysql.config.PartitionConfig;
import com.partition.mysql.em.RangeStrategyEnum;
import com.partition.mysql.handle.CompositePartitionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * ClassName: PartitionInitial <br/>
 * Description: 启动时初始化表分区配置  <br/>
 * Date: 2022/04/11 <br/>
 *
 * @author hexinglin
 * @version 1.0.0
 * @since 1.8
 */
@Component
//@ConditionalOnProperty(prefix = "partition.config", name = "partitionOnStartup", havingValue = "true")
public class PartitionInit implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(PartitionInit.class);

    /**
     * 应用配置文件
     */
    @Autowired
    private PartitionConfig partitionConfig;

    /**
     * 处理策略
     */
    @Autowired
    private CompositePartitionHandler compositePartitionHandler;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        Boolean partitionOnStartup = partitionConfig.getPartitionEnable();
        List<PartitionItem> partItems = partitionConfig.getPartItems();

        if (!partitionOnStartup|| CollectionUtils.isEmpty(partItems)){
            //没有开启表分区或没有配置定时分区表，不执行定时任务
            return;
        }
        logger.info("---------开始表分区处理----------");
        try {
            partitionConfig();
        }catch (Exception e) {
            logger.error("表分区处理异常，{}",e.getMessage());
        }
        logger.info("---------完成表分区处理----------");
    }

    private void partitionConfig() {
        List<PartitionItem> partItems = partitionConfig.getPartItems();
        if (!CollectionUtils.isEmpty(partItems)){
            for (PartitionItem partItem : partItems) {
                compositePartitionHandler.partition(partItem, RangeStrategyEnum.getByCode(partItem.getRangeStrategy()));
            }
        }
    }


}
